package cn.com.greatwall.common.filter;

import java.io.IOException;
import java.util.logging.Filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.filter.OncePerRequestFilter;

import cn.com.greatwall.common.constant.CommonConstant;
import cn.com.greatwall.common.constant.SecurityConstants;
import cn.com.greatwall.common.context.TenantContextHolder;
import cn.hutool.core.util.StrUtil;

/**
 * @Author herw
 * @Time 2022-02-16 10:41:54
 * @Version 1.0
 * @Description: 租户过滤器
 */
@ConditionalOnClass(Filter.class)
public class TenantFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            // 优先获取请求参数中的tenantId值
            String tenantId = request.getParameter(CommonConstant.TENANT_ID_PARAM);
            if (StrUtil.isEmpty(tenantId)) {
                tenantId = request.getHeader(SecurityConstants.TENANT_HEADER);
            }
            //保存租户id
            if (StrUtil.isNotEmpty(tenantId)) {
                TenantContextHolder.setTenant(tenantId);
            }
            
            filterChain.doFilter(request, response);
        } finally {
            TenantContextHolder.clear();
        }
    }

}
